<template>
  <div :class="['table-list-container', { 'close-width': isClosedRef }]">
    <BaseLoading v-if="isLoadingRef" />
    <a-table
      bordered
      :data-source="props.staffList"
      :columns="columns(userInfo?.identity)"
      :row-selection="rowSelection"
      :pagination="false"
      :scroll="{ x: true }"
      :loading="isLoadingRef"
      :rowKey="(record) => record?.staffId"
    >
      <template #bodyCell="{ column, text, record }">
        <!-- 姓名 -->
        <template v-if="column.dataIndex === 'staffName'">
          <div class="editable-cell">
            <!-- 编辑状态 -->
            <div
              class="editable-cell-input-wrapper"
              v-if="editableData[record.staffId]"
            >
              <a-input
                v-model:value="editableData[record.staffId].staffName"
                @pressEnter="handleSave(record.staffId)"
              />
              <span
                class="editable-cell-icon-save"
                @click="handleSave(record.staffId)"
              >
                <BaseIcon type="save" />
              </span>
            </div>
            <!-- 展示状态 -->
            <div class="editable-cell-text-wrapper" v-else>
              {{ text || " " }}
              <span
                class="editable-cell-icon-edit"
                @click="handleEdit(record.staffId)"
              >
                <BaseIcon type="edit" />
              </span>
            </div>
          </div>
        </template>

        <!-- 详情 -->
        <template v-if="column.dataIndex === 'staffId'">
          <a-tag @click="openDetail(record.staffId)" style="cursor: pointer;">{{ text ? "查看" : "暂无" }}</a-tag>
        </template>
        <!-- 性别 -->
        <template v-if="column.dataIndex === 'gender'">
          <a-tag>{{ text === 1 ? "男" : "女" }}</a-tag>
        </template>
        <!-- 职级描述 -->
        <template
          v-if="
            column.dataIndex === 'levelInfo' &&
            column.key === 'levelDescription'
          "
        >
          {{ text?.levelDescription ? text?.levelDescription : "暂无职级描述" }}
        </template>

        <!-- 部门 -->
        <template
          v-if="
            column.dataIndex === 'departmentInfo' &&
            column.key === 'departmentName'
          "
        >
          {{ text?.departmentName ? text?.departmentName : "暂无部门" }}
        </template>
        <!-- 部门领导 -->
        <template
          v-if="
            column.dataIndex === 'departmentInfo' &&
            column.key === 'departmentLeader'
          "
        >
          {{ text?.departmentLeader ? text?.departmentLeader : "暂无部门领导" }}
        </template>
        <!-- 学历 -->
        <template v-if="column.dataIndex === 'educationType'">
          <a-tag>
            {{
              map.educationTypes.has(text) ? map.educationTypes.get(text) : "--"
            }}
          </a-tag>
        </template>
        <!-- 婚姻状况 -->
        <template v-if="column.dataIndex === 'isMarriage'">
          <a-tag class="cursor-pointer">
            {{ text?.isMarriage ? "已婚" : "未婚" }}
          </a-tag>
        </template>
        <!-- 绩效考核 -->
        <template
          v-if="column.dataIndex === 'record' && column.key === 'assessment'"
        >
          <a-tag
            class="cursor-pointer"
            @click="
              handleOpenRecord({
                title: '考核记录',
                type: 'assessment',
                interface: 'getAssessmentList',
                requestData: {
                  queryData: {
                    staffId: record.staffId
                  }
                }
              })
            "
          >
            {{ "查看" }}
          </a-tag>
        </template>
        <!-- 奖惩记录 -->
        <template
          v-if="
            column.dataIndex === 'record' && column.key === 'rewardPunishRecord'
          "
        >
          <a-tag class="cursor-pointer" @click="handleOpenRecord(record)">
            {{ "查看" }}
          </a-tag>
        </template>
        <!-- 调薪记录 -->
        <template
          v-if="
            column.dataIndex === 'record' && column.key === 'salaryAdjustment'
          "
        >
          <a-tag class="cursor-pointer" @click="handleOpenRecord(record)">
            {{ "查看" }}
          </a-tag>
        </template>
      </template>
    </a-table>
    <BaseDialog
      :title="currentRecordRef?.title"
      :dialogStatus="dialogStatusRef"
      :setDialogStatus="setDislogStatus"
    >
      <RecordTable
        :type="currentRecordRef?.type"
        :interface="currentRecordRef?.interface"
        :requestData="currentRecordRef?.requestData"
      />
    </BaseDialog>

    <!-- <a-modal
      title="props.title"
      v-model:visible="dialogStatusRef"
      width="600"
      centered="true"
    >
      1111
    </a-modal> -->
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onBeforeMount, Ref, toRefs, UnwrapRef } from "vue";
import { computed, defineComponent, reactive, ref } from "vue";
import { cloneDeep } from "lodash-es";
import columns from "../colums";
import map from "../../../utils/map";
import BaseDialog from "../../../components/base-dialog/index.vue";
import RecordTable from "./RecordTable.vue";
import { storeToRefs } from "pinia";
import appStore from "@/store";
import { tuple } from "ant-design-vue/lib/_util/type";
import { message } from "ant-design-vue";
const { proxy } = getCurrentInstance();
import apis from '@/apis/index';
const useStaffStore = proxy.$appStore.useStaffStore;
const useCommonStore = proxy.$appStore.useCommonStore;
const { isClosedRef } = storeToRefs(useStaffStore);
interface DataItem {
  staffId: number;
  staffName: string;
  mobile: string;
  levelInfo: object;
}
interface PropTypes {
  staffList: DataItem[];
}
// console.log(props.staffList, "props-staffList");
const props = withDefaults(defineProps<PropTypes>(), {
  staffList: []
});
const { idsRef, setIsShowDetailDrawer, isShowDetailDrawer} = storeToRefs(useCommonStore);



const onSelectChange = (keys) => {
  console.log(keys, idsRef);
  const arr:any = [
    ...idsRef.value,
    ...keys,
  ];
  idsRef.value = arr;
  // updateIds(keys);
}

const rowSelection = reactive({
  selectedRowKeys: idsRef,
  onChange: onSelectChange,
});




const userInfo = JSON.parse(sessionStorage.getItem("userInfo") || '');
console.log(userInfo, "user");

const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});


async function handleSave(key: string) {
  console.log(key, editableData[key], "handleSave");
  Object.assign(
    props.staffList.filter((item) => key === item.staffId)[0],
    // dataSource.value.filter((item) => key === item.key)[0],
    editableData[key]
  );
  const val = editableData[key]?.staffName || '';
  const params = {
    staffId: key,
    updateType: 'userName',
    updateValue: val,
  };
  const res = await apis.staff.updateStaff_API(params);
  console.log('res','dddddddddddddddddd') 
  message.success('员工修改成功');
  delete editableData[key];
  
  
}


async function handleEdit (key: string) {
  console.log(key, editableData, "handleEdit");
  // console.log(props.staffList.filter((item) => key === item.key)[0]);
  // console.log(props.staffList.filter((item) => console.log(item)));
  editableData[key] = cloneDeep(
    props.staffList.filter((item) => key === item.staffId)[0]
  );
  // dataSource.value.filter((item) => key === item.key)[0]
  console.log(editableData[31], "edit");
  // setIsShowDetailDrawer(true);
  // isShowDetailDrawer.value = true;
  // await appStore.useStaffStore.getStaffDetail(+key)
}// @ts-ignore
const { isLoadingRef } = storeToRefs(
  proxy.$appStore.useStaffStore
);

// dialog打开状态
const dialogStatusRef = ref(false);
function setDislogStatus(bool: boolean) {
  dialogStatusRef.value = bool;
}
const currentRecordRef = ref({});
function setCurrentRecord(obj: object) {
  currentRecordRef.value = obj;
}
// 处理打开查看记录的dialog
function handleOpenRecord(record) {
  console.log(record);
  // 记录当前数据
  setCurrentRecord(record);
  console.log(currentRecordRef, "currentRecordRef");
  // 设置dialog的打开状态
  setDislogStatus(true);
}

onBeforeMount(() => {
  console.log("onBeforeMount");
});
onMounted(async () => {
  try {
    // await initStaffList();
    console.log("onMounted-table-list");
    // const { isLoadingRef, staffListRef } = storeToRefs(
    //   proxy.$appStore.useStaffStore
    // );
  } catch (error) {
    console.log(error, "onMounted-员工管理table");
  }
});


async function openDetail (key) {
  await appStore.useStaffStore.getStaffDetail(+key)
  setTimeout(() => {
    isShowDetailDrawer.value = true;
  }, 300);
}


function _setIsShowDetailDrawer(arg0: boolean) {
throw new Error("Function not implemented.");
}
</script>

<style lang="less">
.table-list-container {
  width: calc(100% - 260px);
  margin-top: 1px;
  margin-left: 1px;
  &.close-width {
    width: 100%;
  }
}

.ant-table-row {
  height: 60px;
  box-sizing: border-box;
  // background-color: #108ee9;
}

.ant-table-cell {
  height: 60px;
  box-sizing: border-box;
}

.editable-cell {
  position: relative;
  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 24px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 24px 10px 14px;
    // background-color: #f40;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .editable-cell-icon-edit,
  .editable-cell-icon-save {
    position: absolute;
    right: 0;
    width: 30px;
    height: 30px;
    line-height: 30px;
    cursor: pointer;
    // background-color: #555;
    margin-right: 2px;
    // display: flex;
    // justify-content: center;
    // align-items: center;
    span {
      width: 40px;
      height: 30px;
    }
  }

  .editable-cell-icon-edit {
    margin-top: 4px;
    // display: none;
  }

  .editable-cell-icon-save {
    line-height: 30px;
  }

  .editable-cell-icon-edit:hover,
  .editable-cell-icon-save:hover {
    color: #108ee9;
  }
  span.anticon {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
// .editable-cell:hover .editable-cell-icon-edit {
//   display: inline-block;
// }

// span {
//   width: 30px;
//   height: 30px;
//   // display: flex;
//   // justify-content: center;
//   // align-items: center;
// }

.ant-input {
  width: 130px;
}
</style>
